package com.xjy.controller;

import com.github.pagehelper.PageInfo;
import com.xjy.pojo.*;
import com.xjy.service.adminService;
import com.xjy.service.orderService;
import com.xjy.service.pathService;
import com.xjy.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@Controller
public class adminController {
    @Autowired
    @Qualifier("adminServiceImpl")
    private adminService adminService;
    @Autowired
    @Qualifier("userServiceImpl")
    private userService userService;
    @Autowired
    @Qualifier("orderServiceImpl")
    private orderService orderService;
    @Autowired
    @Qualifier("pathServiceImpl")
    private pathService pathService;

    @RequestMapping("/admin/toLoginPage")
    public String toLoginPage(){
        return "jsp/adminLogin";
    }

    @RequestMapping("/admin/login")
    public String login(String adminname, String password, Model model, HttpSession session){
        Admin admin = adminService.getAdminByName(adminname);
        if (admin != null) {
            System.out.println(admin.getPwd().equals(password));
            if (admin.getPwd().equals(password)) {
                session.setAttribute("adminInfo",admin);
                return "jsp/adminIndex";
            }else {
                model.addAttribute("loginError","密码输入错误");
                return "jsp/adminLogin";
            }

        }else {
            model.addAttribute("loginError","该用户不存在");
            return "jsp/adminLogin";
        }
    }

    @RequestMapping("/admin/loginOut")
    public String loginOut(HttpSession session){
        session.removeAttribute("adminInfo");
        return "jsp/adminLogin";
    }

    @RequestMapping("/admin/allAdmin")
    public String allAdmin(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "5") int size, Model model){
        List<Admin> admins = adminService.findAllAdminsByPage(page,size);
        //PageInfo就是一个分页Bean
        PageInfo pageInfo = new PageInfo(admins);
        model.addAttribute("PageInfo",pageInfo);
        return "jsp/allAdmin";
    }

    @RequestMapping("/admin/deleteAdmin")
    public String deleteAdmin(int aid){
        System.out.println("deleteAdmin===>"+aid);
        adminService.deleteAdmin(aid);
        return "redirect:/admin/allAdmin";
    }

    @RequestMapping("/admin/allUser")
    public String allUser(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "5") int size,Model model){
        List<User> users = userService.findAllUsersByPage(page,size);
        //PageInfo就是一个分页Bean
        PageInfo pageInfo = new PageInfo(users);
        model.addAttribute("PageInfo",pageInfo);
        return "jsp/allUser";
    }

    //查询用户
    @RequestMapping("/admin/getUserByName")
    public String getUserByName(String username,Model model){
        System.out.println("getUserByName==>"+username);
        User user= userService.getUserByName(username);
        List<User> users =new ArrayList<User>();
        if (user == null) {
            users = userService.getUsers();
            model.addAttribute("queryError","未查到该用户");
        }else {
            users.add(user);
        }
        model.addAttribute("list",users);
        return "jsp/allUser";
    }

    //删除用户
    @RequestMapping("/admin/deleteUser")
    public String deleteUser(int uid){
        System.out.println("deleteUser==>"+uid);
        userService.userDelete(uid);
        return "redirect:/admin/allUser";
    }


    @RequestMapping("/admin/allPath")
    public String allPath(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "10") int size,Model model){
        List<Path> pathList = pathService.getPathList(page,size);
        for (Path path : pathList) {
            if(path.getPicid()==null){
                path.setPicid(UUID.randomUUID().toString().replaceAll("-",""));
                pathService.updatePath(path);
            }
        }
        System.out.println(pathList);
        PageInfo pathInfo = new PageInfo(pathList);
        model.addAttribute("PageInfo",pathInfo);
        return "jsp/allPath";
    }

    @RequestMapping("/admin/toAddPath")
    public String toAddPath(){
        return "jsp/addPath";
    }

    @RequestMapping("/admin/addPath")
    public String addPath(@RequestParam("file") CommonsMultipartFile file,
                          String pid,
                          String pathname,
                          String province,
                          String city,
                          int daytime,
                          Double price,
                          String intro,
                          String descr
            , HttpServletRequest request) throws IOException {
        //上传路径保存设置
        String filePath =request.getServletContext().getRealPath("/upload");
        File realPath =new File(filePath);
        if (!realPath.exists()) {
            realPath.mkdirs();
        }
        //上传文件地址
        System.out.println("上传文件保存地址："+realPath);
        //获取原始图片的拓展名
        String originalFilename = file.getOriginalFilename();
        //新的文件名字
        String newFileName = UUID.randomUUID().toString().replaceAll("-","")+originalFilename;
        //封装上传文件位置的全路径
        File targetFile = new File(filePath,newFileName);
        //通过CommonsMultipartFile的方法直接写文件
        file.transferTo(targetFile);

        String picid=UUID.randomUUID().toString().replaceAll("-","");
        Path path =new Path(pid,pathname,province,city,daytime,price,intro,newFileName,descr,picid, 0, 1);
        pathService.addPath(path);

        return "redirect:/admin/allPath";
    }


    @RequestMapping("/admin/toUpdatePath")
    public String toUpdatePath(String pid,Model model){
        Path path = pathService.getPathInfoById(pid);
        System.out.println("pathInfo===>"+path);
        model.addAttribute("PageInfo",path);
        return "jsp/updatePath";
    }


    @RequestMapping("/admin/updatePath")
    public String updatePath(MultipartFile file,
                             String pid,
                             String pathname,
                             String province,
                             String city,
                             int daytime,
                             Double price,
                             String intro,
                             String descr,
                             int status
            , HttpServletRequest request,RedirectAttributes attr) throws IOException {

        //通过ID查询到要修改的文件在数据库中的数据
        Path path = pathService.getPathById(pid);
        path.setPathname(pathname);
        path.setProvince(province);
        path.setCity(city);
        path.setDaytime(daytime);
        path.setPrice(price);
        path.setIntro(intro);
        path.setDescr(descr);
        path.setStatus(status);

        //获取文件上传的路径
        String filePath =request.getServletContext().getRealPath("/upload");
        //生成文件的名字
        String fileName = UUID.randomUUID().toString().replaceAll("-","")+file.getOriginalFilename();
        if (!file.isEmpty()){
            //获取上传文件的路径
            File fil=new File(filePath);
            //获取所有文件
            File[] files = fil.listFiles();
            for (int i = 0; i < files.length; i++) {
                //当该文件的名字和我们从数据库中查到的名字相同时删除
                if (files[i].getName().equals(path.getPics())){
                    files[i].delete();
                }
            }
            //吧新上传的文件传入指定位置
            //封装上传文件位置的全路径
            File targetFile = new File(filePath,fileName);
            //通过CommonsMultipartFile的方法直接写文件
            file.transferTo(targetFile);
            //设置新的路径名称
            path.setPics(fileName);
            //调用修改方法
            pathService.updatePath(path);

        }else {
            pathService.updatePath(path);
        }
        attr.addAttribute("pid", pid);
        return "redirect:/admin/toUpdatePath";

    }

    @RequestMapping("/admin/updatePathPic")
    public String updatePathPic(String pid, String picid, String oldPic, MultipartFile newPicture, HttpServletRequest request, RedirectAttributes attr) throws IOException {
        Map<String, String> map = new HashMap<>();
        map.put("picid",picid);
        map.put("oldPic",oldPic);

        String filePath =request.getServletContext().getRealPath("/upload");
        File realPath = new File(filePath);
        if (!realPath.exists()) {
            realPath.mkdirs();
        }
        String  fileName = UUID.randomUUID().toString().replaceAll("-","")+newPicture.getOriginalFilename();;
        File targetFile = new File(filePath,fileName);
        newPicture.transferTo(targetFile);
        map.put("newPic",fileName);
        pathService.updatePathPic(map);

        System.out.println("删除文件");
        File[] files = realPath.listFiles();
        for (int i = 0; i < files.length; i++) {
            //当该文件的名字和我们从数据库中查到的名字相同时删除
            if (files[i].getName().equals(oldPic)){
                files[i].delete();
            }
        }

        //跳转地址带上oid参数
        attr.addAttribute("pid", pid);
        return "redirect:/admin/toUpdatePath";
    }

    @RequestMapping("/admin/addPathPic")
    public String addPathPic(String pid,String picid,MultipartFile newPic,HttpServletRequest request,RedirectAttributes attr) throws IOException {
        String filePath =request.getServletContext().getRealPath("/upload");
        File realPath = new File(filePath);
        if (!realPath.exists()) {
            realPath.mkdirs();
        }
        String  fileName = UUID.randomUUID().toString().replaceAll("-","")+newPic.getOriginalFilename();;
        File targetFile = new File(filePath,fileName);
        newPic.transferTo(targetFile);
        pathService.addPathPic(picid,fileName);

        //跳转地址带上oid参数
        attr.addAttribute("pid", pid);
        return "redirect:/admin/toUpdatePath";

    }

    @RequestMapping("/admin/deletePathPic")
    public String deletePathPic(String pid,String picid,String oldPic,HttpServletRequest request,RedirectAttributes attr) throws IOException {
        String filePath =request.getServletContext().getRealPath("/upload");
        File realPath = new File(filePath);
        if (!realPath.exists()) {
            realPath.mkdirs();
        }
        System.out.println("删除文件");
        File[] files = realPath.listFiles();
        for (int i = 0; i < files.length; i++) {
            //当该文件的名字和我们从数据库中查到的名字相同时删除
            if (files[i].getName().equals(oldPic)){
                files[i].delete();
            }
        }
        pathService.deletePathPic(picid,oldPic);


        //跳转地址带上oid参数
        attr.addAttribute("pid", pid);
        return "redirect:/admin/toUpdatePath";

    }

    @RequestMapping("/admin/allNoPay")
    public String allNoPay(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "10") int size,Model model){
        List<Map> orders = orderService.getOrderByStatus(0,page,size);
        /*0->待付款；1->待审核；2->等待开始；3->进行中完成；4->已完成，未评论；5->已关闭；6->无效订单。*/
        PageInfo pageInfo = new PageInfo(orders);
        model.addAttribute("title","未支付,请提醒");
        model.addAttribute("page","/admin/allNoPay");
        model.addAttribute("PageInfo",pageInfo);
        model.addAttribute("operate","/admin/remind?oid=");
        model.addAttribute("operationName","提醒");
        return "jsp/orderManage";
    }

    @RequestMapping("/admin/allNoReview")
    public String allNoReview(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "10") int size,Model model){
        List<Map> orders = orderService.getOrderByStatus(1,page,size);
        System.out.println(orders);
        /*0->待付款；1->待审核；2->等待开始；3->进行中完成；4->已完成，未评论；5->已关闭；6->无效订单。*/
        PageInfo pageInfo = new PageInfo(orders);
        model.addAttribute("title","未审核,请审核");
        model.addAttribute("page","/admin/allNoReview");
        model.addAttribute("PageInfo",pageInfo);
        model.addAttribute("operate","/admin/toOrderInfo?oid=");
        model.addAttribute("operationName","审核");
        return "jsp/orderManage";
    }

    @RequestMapping("/admin/check")
    public String check(String oid,int status){
        int uid =orderService.getUidByOid(oid);
        String mid = UUID.randomUUID().toString().replaceAll("-","");
        Date date = new Date();
        Message message = new Message(mid,uid,"",2,date);
        if(status == 1){
            //如果通过审核，发消息通过，且将状态改为未开始
            message.setMsg("审核已通过");
            orderService.updateOrder(oid,3);
        }else if (status == 2) {
            message.setMsg("审核未通过，请重新填写个人信息");
        }
        adminService.addMessage(message);
        return "redirect:/admin/allNoReview";
    }

    @RequestMapping("/admin/allNoReply")
    public String allNoReply(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "10") int size,Model model){
        List<Map> orders = orderService.getOrderByStatus(4,page,size);
        /*0->待付款；1->待审核；2->等待开始；3->进行中完成；4->已完成，未评论；5->已关闭；6->无效订单。*/
        PageInfo pageInfo = new PageInfo(orders);
        model.addAttribute("title","未评论,请提醒");
        model.addAttribute("page","/admin/allNoReply");
        model.addAttribute("PageInfo",pageInfo);
        model.addAttribute("operate","/admin/toReply?oid=");
        model.addAttribute("operationName","删除");
        return "jsp/orderManage";
    }

    @RequestMapping("/admin/toReply")
    public String toReply(String oid,Model model){
        Comment comment =orderService.getComment(oid);
        System.out.println(comment);
        model.addAttribute("comments",comment);
        return "jsp/allComment";
    }

    @RequestMapping("/admin/toOrderInfo")
    public String toOrderInfo(String oid,Model model){
        Order order = orderService.getOrderById(oid);
        List<OrderInfo> orderInfos = orderService.getOrderInfos(oid);
        PageInfo pageInfo = new PageInfo(orderInfos);
        model.addAttribute("order",order);
        model.addAttribute("orderInfos",pageInfo);
        return "jsp/orderInfo";
    }

    @RequestMapping("/admin/allInvalid")
    public String allInvalid(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "10") int size,Model model){
        List<Map> orders = orderService.getOrderByStatus(6,page,size);
        /*0->待付款；1->待审核；2->等待开始；3->进行中完成；4->已完成，未评论；5->已关闭；6->无效订单。*/
        PageInfo pageInfo = new PageInfo(orders);
        model.addAttribute("title","无效订单");
        model.addAttribute("page","/admin/allNoReply");
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("operate","/admin/deleteOrder?oid=");
        model.addAttribute("operationName","删除");
        return "jsp/orderManage";
    }

    @RequestMapping("/admin/deleteOrder")
    public String deleteOrder(String oid,HttpServletResponse response) throws IOException {
        PrintWriter out = null;
        response.setContentType("text/html; charset=UTF-8"); //转码
        out = response.getWriter();

        Order order = orderService.getOrderById(oid);
        if (order.getStatus()!=6) {
            out.write("<script>");
            out.write("alert('订单无法删除');");
            out.write("location.href='/back_war_/admin/allInvalid'");
            out.write("</script>");
            out.close();
            return null;
        }
        System.out.println("deleteOrder===>"+order);
        orderService.deleteOrder(oid);
        orderService.deleteOrderInfo(oid);

        return "redirect:/admin/allInvalid";
    }

    @RequestMapping("/admin/allComment")
    public String allComment(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "10") int size,Model model){
        List<Map> comments =orderService.getComments(page,size);
        System.out.println(comments);
        PageInfo PageInfo = new PageInfo(comments);
        model.addAttribute("comments",PageInfo);
        return "jsp/allComment";

    }

    @RequestMapping("/admin/updateReply")
    public String updateReply(String oid,String reply){
        System.out.println("updateComment========>");
        orderService.updateReply(oid, reply);
        return "redirect:/admin/allComment";
    }

    /*@RequestMapping()*/
    @RequestMapping("/admin/addMessage")
    public String addMessage(String msg,String oid,int type){
        int uid =orderService.getUidByOid(oid);
        String mid = UUID.randomUUID().toString().replaceAll("-","");
        Date date = new Date();
        Message message = new Message(mid,uid,msg,type,date);
        System.out.println("addmsg=====>"+message);
        adminService.addMessage(message);

        return "redirect:/admin/allOrder";
    }

    @RequestMapping("/admin/allNotice")
    public String allNotice(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "10") int size,Model model){
        List<Message> notices = adminService.getNotices(page,size);
        PageInfo pageInfo = new PageInfo(notices);
        model.addAttribute("PageInfo",pageInfo);
        return "jsp/allNotice";

    }

    @RequestMapping("/admin/addNotice")
    public String addNotice(String msg){
        String mid = UUID.randomUUID().toString().replaceAll("-", "");
        Date date = new Date();
        Message message = new Message(mid,msg,1,date);
        adminService.addMessage(message);
        return "redirect:/admin/allNotice";
    }

    @RequestMapping("/admin/updateNotice")
    public String updateNotice(String notice,String mid){
        adminService.updateNotice(mid,notice);
        return "redirect:/admin/allNotice";
    }

    @RequestMapping("/admin/deleteNotice")
    public String deleteNotice(String mid){
        adminService.deleteNotice(mid);
        return "redirect:/admin/allNotice";
    }






}